package com.redwine.app;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.MultipartRequest;
import com.redwine.app.net.responses.RedwineDetailResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.utils.Settings;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 申请供应商最后一步
 * 作者：gassion on 17/8/7 22:46
 * 最可怕的敌人，就是没有坚强的信念。
 */

public class ApplyForSupplierLastActivity extends BaseActivity {

    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.layout_back)
    private LinearLayout layoutBack;
    public static final String PUBLISH_ENTITY = "publishEntity";
    private RedwineDetailResponse.DataEntity.PublishEntity publishEntity;
    private boolean isIdNumber = false;
    private List<String> idNumberPics = new ArrayList<>();//身份证集合
    private List<String> licenseNumberPics = new ArrayList<>();//营业执照的集合
    @ViewInject(R.id.supplier_last_iv_id_number_photo)
    private ImageView mSupplierLastIvIdNumberPhoto;
    @ViewInject(R.id.supplier_last_iv_license_number_photo)
    private ImageView mSupplierLastIvLicenseNumberPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_for_supplier_last);
        ViewUtils.inject(this);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        if (null != intent) {
            publishEntity = (RedwineDetailResponse.DataEntity.PublishEntity) intent.getSerializableExtra(PUBLISH_ENTITY);
        }
        headerTitle.setText(R.string.supplier_certification);
        layoutBack.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.layout_back, R.id.supplier_last_iv_id_number_photo, R.id.supplier_last_iv_license_number_photo, R.id.supplier_last_tv_submit})
    public void mClick(View v) {
        switch (v.getId()) {

            case R.id.layout_back:
                finish();
                break;

            case R.id.supplier_last_tv_submit:
                requestRegisterData();
                break;

            case R.id.supplier_last_iv_id_number_photo:
                isIdNumber = true;
                choosePhotoDialog();
                break;

            case R.id.supplier_last_iv_license_number_photo:
                isIdNumber = false;
                choosePhotoDialog();
                break;
        }
    }

    @Override
    protected void photoCallBack(String path) {
        if (isIdNumber) {
            idNumberPics.add(path);
            BitmapUtils.loadImage(mSupplierLastIvIdNumberPhoto, path, BitmapUtils.BANNER);
        } else {
            licenseNumberPics.add(path);
            BitmapUtils.loadImage(mSupplierLastIvLicenseNumberPhoto, path, BitmapUtils.BANNER);
        }
    }


    /**
     * 申请成为供应商
     */
    private void requestRegisterData() {

        if (idNumberPics.isEmpty()) {
            showToast("身份证证件照不能为空！");
            return;
        }

        if (licenseNumberPics.isEmpty()) {
            showToast("营业执照不能为空！");
            return;
        }

        final List<File> files = new ArrayList<>();
        for (int i = 0; i < idNumberPics.size(); i++) {
            files.add(new File(idNumberPics.get(i)));
        }

        for (int i = 0; i < licenseNumberPics.size(); i++) {
            files.add(new File(licenseNumberPics.get(i)));
        }

        if (!NetUtil.checkNet(this)) {
            showToast(R.string.generic_check);
            return;
        }

        showWaiting();
        String url = NetworkConstants.SUPPLIER_REGISTER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("type", publishEntity.getSupplierType());
        params.put("title", publishEntity.getVendorName());
        params.put("name", publishEntity.getRealName());
        params.put("id_num", publishEntity.getIdNumber());
        params.put("tax_num", publishEntity.getLicenseNumber());
        MultipartRequest<BaseResponse> multipartRequest = new MultipartRequest<>(url, BaseResponse.class, "images", files, params,
                new Response.Listener<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response) {
                        dismissWaiting();
                        showToast(response.getMsg());
                        if (response.isSuccess()) {
                            Settings.setSharedPreferences(Settings.SUPPLIER_STATUS, "1");
                            Intent intent = new Intent(ApplyForSupplierLastActivity.this, ApplyForSupplierFinishActivity.class);
                            startActivity(intent);
                            EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.CLOSE_ACTIVITY));
                            finish();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(R.string.generic_check);
            }
        });
        multipartRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 60 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        APP.getInstance().getRequestQueue().add(multipartRequest);
    }
}
